﻿using System;
using System.Collections.Generic;
using Contracts.Entities;
using NLog;

namespace Definition.WebImport
{
    public class TmdbSearch
    {
        protected Logger logger = LogManager.GetCurrentClassLogger();

        private TmdbSearchRequest searchRequest;
        private TmdbGetCover getCover;

        public TmdbSearch()
        {
            this.searchRequest = new TmdbSearchRequest();
            this.getCover = new TmdbGetCover();
        }

        /// <summary>
        /// Request wird einmal für Gruppierung und einmal für Auswertung der Suchergebnisse benötigt
        /// </summary>
        public void Process(object state)
        {         
            var result = new TmdbSearchResult();
            var request = state as string;
           
            result.Items = new List<MovieItem>();       
            result.Request = request;


            try
            {
                logger.Debug(String.Format("Try Search Movies for request {0}", request));

                if (String.IsNullOrEmpty(request))
                    throw new ArgumentNullException("Request has no value");

                //Get Movie
                foreach (var searchResult in searchRequest.Search(request))
                {           
                    //Get Cover
                    var cover = new byte[] { };

                    if (searchResult.Images != null && searchResult.Images.Items != null)
                        cover = getCover.Find(searchResult.Images.Items);
                                   
                    var movieItem = ConvertTmdbSearchMovie.Convert(searchResult, request, cover);
                    result.Items.Add(movieItem);
                }

                result.Success = true;
            }
            catch (Exception e)
            {
                result.Success = false;
                logger.Error(e.Message);
            }
            finally
            {
                OnResult(result);
            }
        }

        public event Action<TmdbSearchResult> OnResult;
    }
}
